package com.banshuibao.bsb_android.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.LiveChatAdapter;
import com.banshuibao.bsb_android.util.LogUtil;
import com.banshuibao.bsb_android.util.StatusBarUtils;
import com.banshuibao.bsb_android.util.XToast;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.DWLiveListener;
import com.bokecc.sdk.mobile.live.DWLivePlayer;
import com.bokecc.sdk.mobile.live.Exception.DWLiveException;
import com.bokecc.sdk.mobile.live.pojo.Answer;
import com.bokecc.sdk.mobile.live.pojo.ChatMessage;
import com.bokecc.sdk.mobile.live.pojo.PrivateChatInfo;
import com.bokecc.sdk.mobile.live.pojo.QualityInfo;
import com.bokecc.sdk.mobile.live.pojo.Question;
import com.bokecc.sdk.mobile.live.pojo.Viewer;
import com.bokecc.sdk.mobile.live.util.HttpUtil;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by zyh on 2017/3/27.
 */

public class LiveDetailActivity extends BaseActivity implements SurfaceHolder.Callback,
        IMediaPlayer.OnPreparedListener,
        IMediaPlayer.OnVideoSizeChangedListener,
        IMediaPlayer.OnErrorListener, IMediaPlayer.OnBufferingUpdateListener,
        View.OnClickListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnInfoListener {

    private final int PUBLIC_MSG = 0;
    private final int PRIVATE_QUESTION_MSG = 1;
    private final int PRIVATE_ANSWER_MSG = 2;
    private final int QUESTION = 10;
    private final int ANSWER = 11;
    private final int USER_COUNT = 20;
    private final int FINISH = 40;
    private final int KICK_OUT = -1;
    private final int RADIO_CHAT = 0;
    private final int RADIO_QUESTION = 1;
    private final int SILENCE_CHAT = 30;
    private final int QUESTION_NOTIFY = 50;

    private boolean isOnPause = false;

    private DWLivePlayer player;
    private SurfaceView sv;
    private SurfaceHolder holder;
    private DWLive dwLive;
    private Button btnFullScreen;
    private RelativeLayout rlPlay;
    private boolean isStop = false;

    private EditText etFullscreen;
    private Button btnFullscreenSendMsg;
    //private TextView chat_btn, question_btn;
    //private View chat_line, question_line;
    private MyHandler handler;
    private TextView tvPlayMsg;
    private LinearLayout rl_bottom, rl_play_top, ll_fullscreen_msg_send;
    private InputMethodManager imm;
    private WindowManager wm;
    private AudioManager audioManager;
    private RecyclerView chatRecyclerView;//, questionRecyclerView;
    private int radio_selection = RADIO_CHAT;
    private Viewer viewer;
    private LiveChatAdapter chatAdapter;
    //private LiveQuestionAdapter questionAdapter;
    private TextView live_title;
    private String title;
    private Runnable r;
    private long oneTime;
    private AlertDialog closeDialog;
    private boolean isClose;
    private LinearLayout question_notify;//, chat_layout, question_layout;
    //private TextView times;
    private int times_count = 3;
    private boolean isLiveComplete;

    private class MyHandler extends Handler {
        WeakReference<LiveDetailActivity> weakReference;

        public MyHandler(LiveDetailActivity liveRoomActivity) {
            weakReference = new WeakReference<>(liveRoomActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (weakReference.get() == null) {
                return;
            }
            switch (msg.what) {
                case PRIVATE_ANSWER_MSG:
                case PUBLIC_MSG:
                    ChatMessage publicMsg = (ChatMessage) msg.obj;
                    if (chatAdapter != null) {
                        chatAdapter.addData(publicMsg);
                        if (chatAdapter.getItemCount() > 0 && radio_selection == RADIO_CHAT)
                            chatRecyclerView.smoothScrollToPosition(chatAdapter.getItemCount() - 1);
                    }
                    break;
                case QUESTION:
                   /* Question question = (Question) msg.obj;
                    if (questionAdapter != null) {
                        LiveQuestionModel liveQuestionModel = new LiveQuestionModel();
                        liveQuestionModel.setName(question.getQuestionUserName());
                        liveQuestionModel.setMsg(question.getContent());
                        liveQuestionModel.setQuestion_id(question.getId());
                        liveQuestionModel.setUser_id(question.getQuestionUserId());
                        questionAdapter.addQuestion(liveQuestionModel);
                        if (questionAdapter.getItemCount() > 0 && radio_selection == RADIO_QUESTION)
                            questionRecyclerView.smoothScrollToPosition(questionAdapter.getItemCount() - 1);
                    }*/
                    break;
                case ANSWER:
                   /* Answer answer = (Answer) msg.obj;
                    if (questionAdapter != null && questionAdapter.getItemCount() > 0) {
                        questionAdapter.addAnswer(answer);
                    }*/
                    break;
                case FINISH:
                    if (isFinish) {
                        return;
                    }
                    isLiveComplete = true;
                    player.pause();
                    player.stop();
                    setHolderBlack("直播结束");
                    if (weakReference != null && weakReference.get() != null)
                        XToast.showToast(weakReference.get(), "直播结束");
                    break;
                case KICK_OUT:
                    XToast.showToast(getApplicationContext(), "您已被踢出");
                    isClose = true;
                    finish();
                    break;
                case SILENCE_CHAT:
                    XToast.showToast(context, "您已被禁言,发送的消息别人无法收到");
                    break;
                case QUESTION_NOTIFY:
                    /*if (isFinish) {
                        return;
                    }
                    times_count--;
                    if (times_count == 0)
                        question_notify.setVisibility(View.GONE);
                    else {
                        times.setText(String.valueOf(times_count + "s"));
                        sendQuestionNotify();
                    }*/
                    break;
                default:
                    break;
            }
        }
    }

    private void hideEditTextSoftInput(EditText editText) {
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //StatusBarUtils.setWindowStatusBarColor(this, android.R.color.transparent);
        setContentView(R.layout.activity_live_detail);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //禁止锁屏
        handler = new MyHandler(this);
        // 初始化audioManager，控制当前声音模式为普通模式
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setMode(AudioManager.MODE_NORMAL);
        wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initData();
        initCurrentView();
        initPlayer();
        initDwLive();
        initListView();
        HttpUtil.LOG_LEVEL = HttpUtil.HttpLogLevel.CLOSE;
    }

    private void initData() {
        title = getIntent().getStringExtra("title");
    }

    private void initCurrentView() {

        tvPlayMsg =  findViewById(R.id.tv_play_msg);
        etFullscreen =  findViewById(R.id.et_fullscreen);
        btnFullscreenSendMsg =  findViewById(R.id.btn_fullscreen_send);
        btnFullscreenSendMsg.setOnClickListener(this);
        btnFullScreen =  findViewById(R.id.btn_full_screen);
        btnFullScreen.setOnClickListener(this);
        rlPlay =  findViewById(R.id.rl_play);
        setRelativeLayoutPlay(true);
        rlPlay.setClickable(true);
        rlPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPrepared) {
                    if (btnFullScreen.getVisibility() == View.VISIBLE) {
                        handler.removeCallbacks(playHideRunnable);
                        setPlayControllerVisible(false);
                    } else {
                        setPlayControllerVisible(true);
                        hidePlayHandler();
                    }
                    if (System.currentTimeMillis() - oneTime <= 500) {
                        setOrientation();
                        return;
                    }
                    oneTime = System.currentTimeMillis();
                }
            }
        });
        rl_play_top =  findViewById(R.id.rl_play_top);
        ll_fullscreen_msg_send =  findViewById(R.id.ll_fullscreen_msg_send);
        live_title =  findViewById(R.id.live_title);
        live_title.setText(title);
        sv =  findViewById(R.id.live_sv);
        holder = sv.getHolder();
        holder.addCallback(this);
        etFullscreen.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    sendMsg();
                    return true;
                }
                return false;
            }
        });
        //question_notify = (LinearLayout) findViewById(R.id.question_notify);
        //times = (TextView) findViewById(R.id.times);
        //sendQuestionNotify();
    }

    private void sendQuestionNotify() {
        if (handler != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (handler != null)
                        handler.sendEmptyMessage(QUESTION_NOTIFY);
                }
            }, 1000);
        }
    }

    private void initListView() {
        rl_bottom =  findViewById(R.id.rl_surfaceview_bottom);
        //chat_layout = (LinearLayout) findViewById(R.id.chat_layout);
       // question_layout = (LinearLayout) findViewById(R.id.question_layout);
        //chat_btn =  findViewById(R.id.chat_btn);
       // question_btn =  findViewById(R.id.question_btn);
       // chat_line = findViewById(R.id.chat_line);
       // question_line = findViewById(R.id.question_line);
        //chat_layout.setOnClickListener(this);
       // question_layout.setOnClickListener(this);
        chatRecyclerView =  findViewById(R.id.listViewChat);
        chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
      //  questionRecyclerView = (RecyclerView) findViewById(R.id.listViewQuestion);
       // questionRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        chatAdapter = new LiveChatAdapter(this, viewer.getId());
       // questionAdapter = new LiveQuestionAdapter(this, viewer.getId());
        chatRecyclerView.setAdapter(chatAdapter);
       // questionRecyclerView.setAdapter(questionAdapter);
    }

    private void scrollToBottom(final RecyclerView recyclerView, final int position) {
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                recyclerView.smoothScrollToPosition(position);
            }
        });
    }

    private void initDwLive() {
        dwLive = DWLive.getInstance();
        dwLive.setDWLivePlayParams(dwLiveListener, getApplicationContext(), null, player);
        viewer = dwLive.getViewer();
    }

    private Runnable playHideRunnable = new Runnable() {

        @Override
        public void run() {
            setPlayControllerVisible(false);
        }
    };

    private void setPlayControllerVisible(boolean isVisible) {
        int visibility = 0;
        if (isVisible) {
            visibility = View.VISIBLE;
        } else {
            visibility = View.INVISIBLE;
        }
        if (!isPortrait()) {
            etFullscreen.requestFocus();
        }
        btnFullScreen.setVisibility(visibility);
    }

    private boolean isPortrait() {
        int mOrientation = getApplicationContext().getResources().getConfiguration().orientation;
        if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            return false;
        } else {
            return true;
        }
    }

    private void hidePlayHandler() {
        handler.removeCallbacks(playHideRunnable);
        handler.postDelayed(playHideRunnable, 5000);
    }

    private void initPlayer() {
        player = new DWLivePlayer(this);
        player.setVolume(1.0f, 1.0f);
        player.setOnPreparedListener(this);
        player.setOnVideoSizeChangedListener(this);
        player.setOnErrorListener(this);
        player.setOnInfoListener(this);
        player.setOnBufferingUpdateListener(this);
        player.setOnCompletionListener(this);
    }

    private boolean isFinish = false;

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacks(r);
            handler.removeCallbacks(playHideRunnable);
            handler = null;
        }
        isFinish = true;
        if (player != null) {
            player.stop();
            player.reset();
            player.release();
            player = null;
        }
        if (dwLive != null) {
            dwLive.onDestroy();
            dwLive = null;
        }
        imm = null;
        etFullscreen = null;
        if (chatAdapter != null) {
            chatAdapter.clear();
            chatAdapter = null;
        }
        /*if (questionAdapter != null) {
            questionAdapter.clear();
            questionAdapter = null;
        }*/
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        if (dwLive != null && !isOnPause) {
            dwLive.start(surfaceHolder.getSurface());
        }
        player.setScreenOnWhilePlaying(true);
        this.holder = surfaceHolder;
        setHolderBlack("正在连接直播中,请稍候……");
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
        LogUtil.e("demo", "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        player.pause();
        player.stop();
        player.reset();
        LogUtil.e("demo", "surfaceDestroyed");
    }

    private boolean isPrepared = false;

    @Override
    public void onPrepared(IMediaPlayer mp) {
        isPrepared = true;
        isLiveComplete = false;
        tvPlayMsg.setVisibility(View.INVISIBLE);
        setPlayControllerVisible(true);
        hidePlayHandler();
        player.start();
    }

    @Override
    public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sar_num, int sar_den) {
        if (width == 0 || height == 0) {
            return;
        }
        tvPlayMsg.setVisibility(View.INVISIBLE);
        sv.setLayoutParams(getVideoSizeParams());
    }

    // 当视频流不可见时，置黑并提示信息
    private void setHolderBlack(String text) {
        tvPlayMsg.setVisibility(View.VISIBLE);
        tvPlayMsg.setText(text);

        SurfaceHolder mHolder = sv.getHolder();
        Canvas canvas = mHolder.lockCanvas();
        if (canvas == null) {
            return;
        }
        canvas.drawColor(Color.BLACK);
        mHolder.unlockCanvasAndPost(canvas);
    }

    // 视频等比缩放
    private RelativeLayout.LayoutParams getVideoSizeParams() {
        int width = 600;
        int height = 400;

        if (isPortrait()) {
            width = wm.getDefaultDisplay().getWidth();
            height = wm.getDefaultDisplay().getHeight() / 3; //TODO 根据当前布局更改
        } else {
            width = wm.getDefaultDisplay().getWidth();
            height = wm.getDefaultDisplay().getHeight();
        }

        int vWidth = player.getVideoWidth();
        int vHeight = player.getVideoHeight();

        if (vWidth == 0) {
            vWidth = 600;
        }
        if (vHeight == 0) {
            vHeight = 400;
        }

        if (vWidth > width || vHeight > height) {
            float wRatio = (float) vWidth / (float) width;
            float hRatio = (float) vHeight / (float) height;
            float ratio = Math.max(wRatio, hRatio);

            width = (int) Math.ceil((float) vWidth / ratio);
            height = (int) Math.ceil((float) vHeight / ratio);
        } else {
            float wRatio = (float) width / (float) vWidth;
            float hRatio = (float) height / (float) vHeight;
            float ratio = Math.min(wRatio, hRatio);

            width = (int) Math.ceil((float) vWidth * ratio);
            height = (int) Math.ceil((float) vHeight * ratio);
        }

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        return params;
    }


    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        LogUtil.e("demo", "=============================>onError:" + what);
        return false;
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer mp, int percent) {
    }

    private DWLiveListener dwLiveListener = new DWLiveListener() {
        @Override
        public void onQuestion(Question question) {
            LogUtil.e("demo", "onQuestion:" + question.toString());
            if (!TextUtils.equals(question.getQuestionUserId(), viewer.getId())) {
                return;
            }
            Message msg = new Message();
            msg.what = QUESTION;
            msg.obj = question;
            handler.sendMessage(msg);
        }

        @Override
        public void onAnswer(Answer answer) {
            LogUtil.e("demo", "onAnswer:" + answer.toString());
            Message msg = new Message();
            msg.what = ANSWER;
            msg.obj = answer;
            handler.sendMessage(msg);
        }

        @Override
        public void onLiveStatus(DWLive.PlayStatus status) {
            LogUtil.e("demo", "onLiveStatusChange:" + status);
            switch (status) {
                case PLAYING:
                    isStop = false;
                    break;
                case PREPARING:
                    isStop = true;
                    break;
            }
        }

        @Override
        public void onPublicChatMessage(ChatMessage msg) {
            LogUtil.e("demo", "onPublicChatMessage:" + msg);
            Message handlerMsg = new Message();
            handlerMsg.what = PUBLIC_MSG;
            handlerMsg.obj = msg;
            handler.sendMessage(handlerMsg);
        }

        @Override
        public void onPrivateQuestionChatMessage(ChatMessage msg) {
            LogUtil.e("demo", "onPrivateQuestionChatMessage:" + msg);
            Message handlerMsg = new Message();
            handlerMsg.what = PRIVATE_QUESTION_MSG;
            handlerMsg.obj = msg;
            handler.sendMessage(handlerMsg);
        }

        @Override
        public void onPrivateAnswerChatMessage(ChatMessage msg) {
            LogUtil.e("demo", "onPrivateAnswerChatMessage:" + msg);
            Message handlerMsg = new Message();
            handlerMsg.what = PRIVATE_ANSWER_MSG;
            handlerMsg.obj = msg;
            handler.sendMessage(handlerMsg);
        }

        @Override
        public void onPrivateChat(PrivateChatInfo privateChatInfo) {

        }

        @Override
        public void onPrivateChatSelf(PrivateChatInfo privateChatInfo) {

        }

        @Override
        public void onUserCountMessage(int count) {
            LogUtil.e("demo",count);
          /*  Message msg = new Message();
            msg.what = USER_COUNT;
            msg.obj = count;
            handler.sendMessage(msg);*/
        }

        @Override
        public void onNotification(String msg) {
            LogUtil.e("demo", "onNotification:" + msg);
        }

        @Override
        public void onInformation(String msg) {
            LogUtil.e("demo", "information:" + msg);
        }

        @Override
        public void onException(DWLiveException exception) {
            LogUtil.e("demo", exception.getMessage() + "");
        }

        @Override
        public void onInitFinished(int playSourceCount, List<QualityInfo> qualityInfoList) {

        }

        @Override
        public void onSilenceUserChatMessage(ChatMessage msg) {
            LogUtil.e("demo", "onSilenceUserChatMessage:" + msg);
            /*Message handlerMsg = new Message();
            handlerMsg.what = PUBLIC_MSG; //收到禁言消息，作为公有消息展示出去，也可以不展示
            handlerMsg.obj = msg;
            handler.sendMessage(handlerMsg);*/
            handler.sendEmptyMessage(SILENCE_CHAT);
        }

        @Override
        public void onKickOut() {
            Message kickOutMsg = new Message();
            kickOutMsg.what = KICK_OUT;
            handler.sendMessage(kickOutMsg);
        }

        @Override
        public void onStreamEnd(boolean isNormal) {
            LogUtil.e("demo", "stream end");
            isStop = true;
            isPrepared = false;
            isLiveComplete = true;
            Message msg = new Message();
            msg.what = FINISH;
            handler.sendMessage(msg);
        }

        @Override
        public void onLivePlayedTime(int playedTime) {
        }

        @Override
        public void onLivePlayedTimeException(Exception exception) {
        }

        @Override
        public void isPlayedBack(boolean isPlayedBack) {
        }

        @Override
        public void onStatisticsParams(Map<String, String> statisticsMap) {
            if (player != null) {
                player.initStatisticsParams(statisticsMap);
            }
        }

        @Override
        public void onCustomMessage(String customMessage) {

        }

        @Override
        public void onBanStream(String s) {

        }

        @Override
        public void onUnbanStream() {

        }

        @Override
        public void onAnnouncement(boolean b, String s) {

        }

        @Override
        public void onRollCall(int i) {

        }

        @Override
        public void onStartLottery(String s) {

        }

        @Override
        public void onLotteryResult(boolean b, String s, String s1, String s2) {

        }

        @Override
        public void onStopLottery(String s) {

        }

        @Override
        public void onVoteStart(int i, int i1) {

        }

        @Override
        public void onVoteStop() {

        }

        @Override
        public void onVoteResult(JSONObject jsonObject) {

        }
    };

    private void setOrientation() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                if (isPortrait()) {
                    finish();
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            case R.id.btn_fullscreen_send:
                sendMsg();
                break;
            case R.id.btn_full_screen:
                setOrientation();
                break;
          /*  case R.id.chat_layout:
                if (radio_selection == RADIO_CHAT)
                    return;
                chat_btn.setTextColor(getResources().getColor(R.color.live_room_yellow_stroke));
                question_btn.setTextColor(getResources().getColor(R.color.white));
                chat_line.setVisibility(View.VISIBLE);
                question_line.setVisibility(View.INVISIBLE);
                radio_selection = RADIO_CHAT;
                etFullscreen.setHint("请输入聊天内容...");
                if (chatAdapter != null) {
                    chatRecyclerView.setVisibility(View.VISIBLE);
                    questionRecyclerView.setVisibility(View.GONE);
                    if (chatAdapter.getItemCount() > 0)
                        scrollToBottom(chatRecyclerView, chatAdapter.getItemCount() - 1);
                }
                break;
            case R.id.question_layout:
                if (radio_selection == RADIO_QUESTION)
                    return;
                question_btn.setTextColor(getResources().getColor(R.color.live_room_yellow_stroke));
                chat_btn.setTextColor(getResources().getColor(R.color.white));
                question_line.setVisibility(View.VISIBLE);
                chat_line.setVisibility(View.INVISIBLE);
                radio_selection = RADIO_QUESTION;
                etFullscreen.setHint("请输入您的问题...");
                if (questionAdapter != null) {
                    questionRecyclerView.setVisibility(View.VISIBLE);
                    chatRecyclerView.setVisibility(View.GONE);
                }
                break;*/
            default:
                break;
        }
    }

    private void sendMsg() {
        //if (radio_selection == RADIO_CHAT)
            sendChatMsg();
        /*else
            sendQuestion();*/
    }

    private void sendChatMsg() {
        String msg = etFullscreen.getText().toString().trim();
        if (!TextUtils.isEmpty(msg)) {
            dwLive.sendPublicChatMsg(msg);
            etFullscreen.setText("");
            hideEditTextSoftInput(etFullscreen);
        } else
            XToast.showToast(context, "您不能发送空消息");
    }

   /* private void sendQuestion() {
        if (isLiveComplete) {
            XToast.showToast(this, "直播已结束，无法继续发布问题");
            return;
        }
        String qaMsg = etFullscreen.getText().toString().trim();
        if (!TextUtils.isEmpty(qaMsg)) {
            try {
                sendQuestion(qaMsg);
                dwLive.sendQuestionMsg(qaMsg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            etFullscreen.setText("");
            hideEditTextSoftInput(etFullscreen);
        } else
            XToast.showToast(context, "您不能发送空消息");
    }*/

   /* private void sendQuestion(String msg) {
        LiveQuestionModel.Body body = new LiveQuestionModel.Body();
        body.setContent(msg);
        com.jieshuibao.biz.http.HttpUtil.doPost(Constants.Url.LIVE_QUESTION_ADD, body, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {

            }
        });
    }*/

    private void resetPlay() {
        if (dwLive != null) {
            dwLive.stop();
            dwLive.start(holder.getSurface());
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setRelativeLayoutPlay(true);
            rl_bottom.setVisibility(View.VISIBLE);
            rl_play_top.setVisibility(View.VISIBLE);
            ll_fullscreen_msg_send.setVisibility(View.VISIBLE);
            btnFullScreen.setBackgroundResource(R.drawable.fullscreen_close);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setRelativeLayoutPlay(false);
            rl_bottom.setVisibility(View.GONE);
            rl_play_top.setVisibility(View.GONE);
            ll_fullscreen_msg_send.setVisibility(View.GONE);
            btnFullScreen.setBackgroundResource(R.drawable.fullscreen_open);
        }
        sv.setLayoutParams(getVideoSizeParams());
        handler.removeCallbacks(playHideRunnable);
        setPlayControllerVisible(true);
        hidePlayHandler();
    }

    @Override
    public void onBackPressed() {
        if (isPortrait()) {
            super.onBackPressed();
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void setRelativeLayoutPlay(boolean isPortraitOrien) {
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        LinearLayout.LayoutParams layoutParams = null;
        if (isPortraitOrien) {
            layoutParams = new LinearLayout.LayoutParams(width, height / 3);
        } else {
            layoutParams = new LinearLayout.LayoutParams(width, height);
        }
        rlPlay.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onInfo(IMediaPlayer arg0, int arg1, int arg2) {
        if (arg1 == IMediaPlayer.MEDIA_INFO_BUFFERING_START) {
            r = new Runnable() {
                @Override
                public void run() {
                    resetPlay();
                }
            };
            handler.postDelayed(r, 10000);
        } else if (arg1 == IMediaPlayer.MEDIA_INFO_BUFFERING_END) {
            if (r != null) {
                handler.removeCallbacks(r);
            }
        }
        return false;
    }

    @Override
    protected void onPause() {
        isPrepared = false;
        isOnPause = true;
        if (player != null && player.isPlaying()) {
            player.pause();
        }
        dwLive.stop();
       /* if (questionAdapter != null) {
            questionAdapter.clearQuestions();
        }*/
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isOnPause) {
            dwLive.start(holder.getSurface());
            isOnPause = false;
        }
    }

    @Override
    public void finish() {
        if (!isClose) {
            showCloseDialog();
            return;
        }
        super.finish();
    }

    private void showCloseDialog() {
        if (closeDialog == null)
            closeDialog = new AlertDialog.Builder(this).setMessage("确定退出直播间?").setPositiveButton("确定退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    isClose = true;
                    finish();
                }
            }).setNegativeButton("不退出", null).create();
        if (!closeDialog.isShowing())
            closeDialog.show();
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        if (dwLive != null && !isStop) {
            resetPlay();
        }
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = etFullscreen;
            if (v != null && isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1] - 20;
            int bottom = top + v.getHeight() + 20;
            int right = left + getWindow().getDecorView().getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
